import { asyncRouterMap, constantRouterMap } from '@/router'
import { getUserRoute } from '@/api/login'
import { Message } from 'element-ui'
import { removeCache, getCookie, setCookie, sessionPut } from '../cache'
/**
 * 通过meta.role判断是否与当前用户权限匹配
 * @param roles
 * @param route
 */
function hasPermission(apiRoute, route) {
  if (route.meta && route.meta.roles) {
    return apiRoute.some(role => route.meta.roles.indexOf(role) >= 0)
  } else {
    return true
  }
}

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param asyncRouterMap
 * @param roleRoute
 */
function filterAsyncRouter(asyncRouterMap, apiRoute) {
  const accessedRouters = asyncRouterMap.filter(route => {
    if (hasPermission(apiRoute, route)) {
      if (route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children, apiRoute)
      }
      return true
    }
    return false
  })
  if (Array.prototype.isPrototypeOf(accessedRouters) && accessedRouters.length > 0) {
    return accessedRouters
  }
}

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: [], // 添加的路由
    api_routes: [],
    user_outlet: [],
    current_outlet: {},
    outlet_id: getCookie('outlet_id')
  },

  mutations: {
    // 吧路由存在 vuex
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    },

    // 存入路由列表
    SET_API_ROUTE: (state, routers) => {
      state.api_routes = routers
      sessionPut('buttonroutes', routers) // 权限路由存在cookie
    },

    // 保存营业点
    SET_OUTLET: (state, outlet) => {
      state.user_outlet = outlet
    },

    // 当前营业点
    CURRENT_OUTLET: (state, aData) => {
      state.current_outlet = aData
      state.outlet_id = aData.id
      setCookie('outlet_id', aData.id)
    },

    LOGOUT: (state) => {
      removeCache('login-username')
      removeCache('login-mobile')
      removeCache('login-token')
      removeCache('login-avatar')
    }
  },
  actions: {

    // 获取用户的路由
    getUserRoute({ commit, state }) {
      return new Promise((resolve, reject) => {
        getUserRoute().then(response => {
          if (response.data.code === 0) {
            const data = response.data.data
            let accessedRouters
            if (data === 'all') {
              accessedRouters = asyncRouterMap
            } else { // 需要过滤
              if (data !== 'null') { // 没有配置权限的
                accessedRouters = filterAsyncRouter(asyncRouterMap, data)
              }
            }
            commit('SET_ROUTERS', accessedRouters)
            commit('SET_API_ROUTE', data)
            resolve()
          } else {
            Message({
              message: response.data.msg,
              type: 'error',
              duration: 5 * 1000
            })
            commit('LOGOUT')
            setTimeout(() => {
              location.reload() // 为了重新实例化vue-router对象 避免bug
            }, 800)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户的路由
    userOutlet({ commit }, aData) {
      commit('SET_OUTLET', aData)
    },

    // 获取用户当前选择的路由
    currentOutlet({ commit }, aData) {
      commit('CURRENT_OUTLET', aData)
    }

  }

}

export default permission
